﻿using System;
using System.Collections;
using System.Data;
using viPage.Providers;
using visinia.SmartEngine.Cache;

namespace viPage.Controllers
{
    /// <summary>
    /// BaseController controls the main settings
    /// </summary>
    public class BaseController
    {
        private const string KEY_BASE_SETTINGS = "viPageBaseSettings";       

        /// <summary>
        /// Gets the setting
        /// </summary>
        /// <param name="key">The settings key to get</param>
        /// <returns>returns the setting value</returns>
        public static string GetSetting(string key)
        {
            if (Settings.Contains(key))
                return (string)Settings[key];
            else
                return string.Empty;
        }

        private static Hashtable _Settings;
        private static Hashtable Settings
        {
            get
            {
                _Settings = (Hashtable)DataCache.GetCache(KEY_BASE_SETTINGS);
                if (_Settings == null)
                {
                    _Settings = new Hashtable();
                    IDataReader dr = viPageDataProvider.Provider.GetBaseSettings();
                    while (dr.Read())
                    {
                        if (dr["SettingName"] != Convert.DBNull)
                        {
                            if (dr["SettingValue"] != Convert.DBNull)
                                _Settings[(string)dr["SettingName"]] = (string)dr["SettingValue"];
                            else
                                _Settings[(string)dr["SettingName"]] = "";
                        }
                    }
                    dr.Close();
                    DataCache.SetCache(KEY_BASE_SETTINGS, _Settings);
                }
                return _Settings;
            }
        }

        #region DATA
        /// <summary>
        /// Adds a new setting Or updates it if it already exists
        /// </summary>
        /// <param name="key">The key to setting</param>
        /// <param name="value">The value of the setting</param>
        public static void AddSetting(string key, string value)
        {
            if (Settings.ContainsKey(key))
                viPageDataProvider.Provider.UpdateBaseSetting(key, value);
            else
                viPageDataProvider.Provider.AddBaseSetting(key, value);
            DataCache.DeleteCacheMultiple("viPage");
        }
        /// <summary>
        /// Deletes the setting
        /// </summary>
        /// <param name="key">The key to delete</param>
        public static void DeleteSetting(string key)
        {
            viPageDataProvider.Provider.DeleteBaseSetting(key);
            DataCache.DeleteCacheMultiple("viPage");
        }
        #endregion
    }
}
